package server;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <h1>Class BuddyList</h1>
 * 
 * A buddy list is a collection of groups of people which contains a
 * user's friends.
 * It implements the Serializable interface since it is going to be
 * sent through the network.
 * 
 * @author Tomas
 * @date March 4 2009
 */
public class BuddyList implements Serializable{

	/**
	 * Required by the Serializable interface
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Collection of the groups in the buddy list.
	 * To be implemented as an ArrayList.
	 */
	protected List<Group> groups = null;
	
	/**
	 * Default constructor. Initializes an instance of the BuddyList class.
	 */
	public BuddyList(){
		
		groups = new ArrayList<Group>();
		
	}
	
	/**
	 * Adds a new group to the buddy list.
	 * @param g
	 * 		Group to be added.
	 */
	public void addGroup(Group g){
		
		groups.add(g);
		
	}
	
	/**
	 * Removes a group from the buddy list. To remove a group, it must be empty,
	 * i.e., it mustn't have any members inside it. This is enforced to avoid
	 * losses of contacts (since they lose the group they belong to).
	 *  
	 * @param g
	 * 		Group to be removed.
	 * @return
	 * 		Boolean operation telling if the operation was successful or not.
	 */
	public boolean removeGroup(Group g){
		
		// If the group is not empty, we shouldn't remove it
		if(g.getMembers().hasNext()){
			return false;
		}
		
		if(groups.contains(g)){
			groups.remove(g);
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * Obtains all the groups in the buddy list.
	 * @return
	 * 		Iterator through the collection of groups.
	 */
	public Iterator<Group> getGroups(){
		
		return groups.iterator();
		
	}
	
	/**
	 * Finds a group in the buddy list.
	 * 
	 * @param name
	 * 		Name of the group
	 * @return
	 * 		Group with that name or null if there is no such group.
	 */
	public Group findGroup(String name){
		
		for(int i = 0; i < groups.size(); i++){
			if(groups.get(i).getName().equals(name)){
				return groups.get(i);
			}
		}
		return null;
	}
}
